﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using kangsuce.Common;
using kangsuce.Model;
using Newtonsoft.Json;
using Senparc.Weixin;
using Senparc.Weixin.MP;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities.Menu;

namespace kangsuce.Admin.Controllers
{
    public class WxSetController : BaseController
    {
        private readonly BLL.WxMenuBLL wxMenuBLL = new BLL.WxMenuBLL();

        /// <summary>
        /// 微信配置信息
        /// </summary>
        /// <returns></returns>
        public ActionResult WxAccount()
        {
            ViewBag.AppId = wxConfig.AppId;
            ViewBag.AppSecret = wxConfig.AppSecret;
            return View();
        }

        /// <summary>
        /// 微信配置信息保存
        /// </summary>
        /// <param name="appId"></param>
        /// <param name="appSecret"></param>
        /// <returns></returns>
        public ActionResult WxAccountSave(string appId = "", string appSecret = "")
        {
            try
            {
                if (appId == "" || appSecret == "")
                {
                    return Json(new {result = "error", msg = "传入参数有误"});
                }
                Dictionary<string, string> nodes = new Dictionary<string, string>
                {
                    {"AppId", appId},
                    {"AppSecret", appSecret}
                };
                Common.Common.UpdateWxConfigText(nodes, Server.MapPath("/config/weixin.xml"));
                return Json(new {result = "success"});
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message});
            }
        }

        /// <summary>
        /// 微信菜单列表
        /// </summary>
        /// <returns></returns>
        public ActionResult WxMenuList()
        {
            var list = wxMenuBLL.GetList(p => p.pId == 0, orderBy: c => c.OrderBy(p => p.menuOrder), selectChird: true);
            ViewBag.List = list;
            return View();
        }

        /// <summary>
        /// 获取微信菜单列表数据
        /// </summary>
        /// <returns></returns>
        public ActionResult GetWxMenuList()
        {
            try
            {
                List<KSC_WxMenu> list = wxMenuBLL.GetList(p => true, orderBy: c => c.OrderBy(p => p.menuOrder));
                return Json(list, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 微信菜单编辑
        /// </summary>
        /// <param name="id"></param>
        /// <param name="pid"></param>
        /// <returns></returns>
        public ActionResult WxMenuEdit(int id = 0, int pid = 0)
        {
            KSC_WxMenu model = wxMenuBLL.GetModelById(id) ?? new KSC_WxMenu {menuId = 0};
            ViewBag.Json = JsonConvert.SerializeObject(model);
            ViewBag.Pid = pid;
            return View();
        }

        /// <summary>
        /// 菜单保存
        /// </summary>
        /// <returns></returns>
        public ActionResult WxMenuSave(KSC_WxMenu model)
        {
            try
            {
                bool result;
                if (model.menuId > 0)
                {
                    KSC_WxMenu upModel = wxMenuBLL.GetModelById(model.menuId);
                    upModel.menuKey = model.menuKey;
                    upModel.menuName = model.menuName;
                    upModel.menuType = model.menuType;
                    upModel.menuUrl = model.menuUrl;
                    upModel.pId = model.pId;
                    result = wxMenuBLL.Update(upModel);
                }
                else
                {
                    int order = 1;
                    List<KSC_WxMenu> list = wxMenuBLL.GetList(p => p.pId == model.pId);
                    if (model.pId == 0)
                    {
                        if (list.Count > 2)
                        {
                            return Json(new { result = "error", msg = "最多只能添加3个一级菜单" });
                        }
                    }
                    else
                    {
                        if (list.Count > 4)
                        {
                            return Json(new { result = "error", msg = "最多只能添加5个子菜单" });
                        }
                    }
                    if (list.Count > 0)
                    {
                        order = list.Max(p => p.menuOrder) + 1;
                    }
                    model.menuOrder = order;
                    result = wxMenuBLL.Insert(model) > 0;
                }
                return Json(new {result = result ? "success" : "error", msg = result ? "保存成功" : "保存错误"});
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message});
            }
        }

        /// <summary>
        /// 微信菜单保存
        /// </summary>
        /// <returns></returns>
        public ActionResult WxMenuSaveToWx()
        {
            try
            {
                ButtonGroup bg = new ButtonGroup();
                List<KSC_WxMenu> list = wxMenuBLL.GetList(p => p.pId == 0, false, p => p.OrderBy(o => o.menuOrder), true);
                foreach (KSC_WxMenu item in list)
                {
                    if (item.chirdList.Count > 0)
                    {
                        SubButton subButton = new SubButton()
                        {
                            name = item.menuName
                        };
                        foreach (KSC_WxMenu chirdItem in item.chirdList)
                        {
                            switch (chirdItem.menuType)
                            {
                                case "view":
                                    subButton.sub_button.Add(new SingleViewButton()
                                    {
                                        url = chirdItem.menuUrl,
                                        name = chirdItem.menuName
                                    });
                                    break;
                                case "click":
                                    subButton.sub_button.Add(new SingleClickButton()
                                    {
                                        key = "SubClickRoot_Music",
                                        name = chirdItem.menuName
                                    });
                                    break;
                            }
                        }
                        bg.button.Add(subButton);
                    }
                    else
                    {
                        switch (item.menuType)
                        {
                            case "view":
                                bg.button.Add(new SingleViewButton()
                                {
                                    name = item.menuName,
                                    url = item.menuUrl
                                });
                                break;
                            case "click":
                                bg.button.Add(new SingleClickButton()
                                {
                                    name = item.menuName,
                                    key = "OneClick"
                                });
                                break;
                        }
                    }
                }
                var result = CommonApi.CreateMenu(access_token, bg);
                return Json(
                    new {result = result.errcode == ReturnCode.请求成功 ? "success" : "error", msg = result.errmsg},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 修改排序
        /// </summary>
        /// <param name="id">菜单id</param>
        /// <param name="sortOrder">排序方式</param>
        /// <returns></returns>
        public ActionResult WxMenuOrderChange(int id = 0, string sortOrder = "")
        {
            try
            {
                KSC_WxMenu wxMenu = wxMenuBLL.GetModelById(id);
                if (wxMenu == null)
                {
                    return Json(new {result = "error", msg = "传入参数有误！"}, JsonRequestBehavior.AllowGet);
                }
                List<KSC_WxMenu> list = wxMenuBLL.GetList(p => p.pId == wxMenu.pId, false,
                    p => p.OrderBy(o => o.menuOrder));
                int index = list.FindIndex(p => p.menuId == id);
                if (sortOrder == "up")
                {
                    if (list[0].menuId == id)
                    {
                        return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
                    }
                    KSC_WxMenu wxMenuNew = wxMenuBLL.GetModelById(list[index - 1].menuId);
                    int order = wxMenuNew.menuOrder;
                    wxMenuNew.menuOrder = wxMenu.menuOrder;
                    wxMenu.menuOrder = order;
                    wxMenuBLL.Update(wxMenu);
                    wxMenuBLL.Update(wxMenuNew);
                }
                else if (sortOrder == "down")
                {
                    if (list[list.Count - 1].menuId == id)
                    {
                        return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
                    }
                    KSC_WxMenu wxMenuNew = wxMenuBLL.GetModelById(list[index + 1].menuId);
                    int order = wxMenuNew.menuOrder;
                    wxMenuNew.menuOrder = wxMenu.menuOrder;
                    wxMenu.menuOrder = order;
                    wxMenuBLL.Update(wxMenu);
                    wxMenuBLL.Update(wxMenuNew);
                }
                else
                {
                    return Json(new {result = "error", msg = "传入参数有误！"}, JsonRequestBehavior.AllowGet);
                }
                return Json(new {result = "success"}, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult WxMenuDelete(int id = 0)
        {
            try
            {
                if (id == 0)
                {
                    return Json(new {result = "error", msg = "传入参数有误"}, JsonRequestBehavior.AllowGet);
                }
                bool result = wxMenuBLL.Delete(id);
                return Json(new {result = result ? "success" : "error", msg = result ? "删除成功" : "删除失败"},
                    JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new {result = "error", msg = ex.Message}, JsonRequestBehavior.AllowGet);
            }
        }
    }
}